package com.wsd.socket.step4;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpParser;

public class Request {
	public Pattern methodRegex = Pattern.compile("(GET|PUT|POST|DELETE|OPTIONS|TRACE|HEAD)");
	private final String body; 
	private final String method; 
	private final Map<String, String> headMap; 
	public Request(Socket socket) throws IOException{
		DataInputStream iptStream = new DataInputStream(socket.getInputStream());
		String methodLine = HttpParser.readLine(iptStream, "UTF-8");
		Matcher m = methodRegex.matcher(methodLine);
		m.find();
		String method = m.group();
		Header[] headers = HttpParser.parseHeaders(iptStream, "UTF-8");
		Map<String, String> headMap = new HashMap<String, String>();
		for(Header h : headers) {
			headMap.put(h.getName(), h.getValue());
		}
		BufferedReader bfReader = new BufferedReader(new InputStreamReader(iptStream));
		StringBuilder body = new StringBuilder();
		char[] buffer = new char[1024];
		
		while(iptStream.available() > 0) {
			bfReader.read(buffer);
			body.append(buffer);
		}
		this.body = body.toString();
		this.method = method;
		this.headMap = headMap;
	}
	public String getBody() {
		return body;
	}
	public String getMethod() {
		return method;
	}
	public Map<String, String> getHeadMap() {
		return headMap;
	}

}
